# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '20180925095740': {  # 幸运 支付宝 定额
        'API_KEY': '434cb1e2cc14471d82a1bfebc9cef7ac',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20180925095646': {  # 万壕 支付宝 定额
        'API_KEY': '8006c6d6a9de4b82baec07b764e34dd0',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20180925095819': {  # 战神 支付宝 定额
        'API_KEY': '94898cbc47884c84914008b6e712d6aa',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20180929104145': {  # dwc 支付宝 定额
        'API_KEY': 'be70b88bc9da4ee9b30f0eb64639c5c2',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20181005104742': {  # 幸运 支付宝 2.7% 60---5000
        'API_KEY': 'f08322fac76b43deb3e1230e44d76ea5',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20181005105916': {  # 万壕 支付宝 2.7% 60---5000
        'API_KEY': '50460e3101a348d3b2f88fa4899370f7',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20181005104837': {  # 战神 支付宝 2.7% 60---5000
        'API_KEY': '67efbcba3e7841e1a146a4cef9480184',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20181005104529': {  # dwc 支付宝 2.7% 60---5000
        'API_KEY': '3203a77791a1406f809f4e600cd31e40',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20181030142503': {  # sp 2.7% (10---5000) D0结算
        'API_KEY': 'aed82bedb4614f3fb06ea52caf3a5b29',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20181029112947': {  # ks 微信 3.2 1～3000
        'API_KEY': '64af4b1f87eb4584bb08ed936e08ccc9',
        'gateway': 'http://w.pcxinfo.com/api/pay',
        'query_gateway': 'http://w.pcxinfo.com/api/query/{}/{}',
    },
    '20181101095403': {  # ks 2.7%（60---3000）D0结算
        'API_KEY': '1edf8d9838804aa3abfd3f86d85eb360',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
    '20190612122440': {  # ks 1.5% 云闪付（10---5000）
        'API_KEY': '06668fb639e34decaf3efe9241bd0a6f',
        'gateway': 'http://p.pcxinfo.com/api/pay',
        'query_gateway': 'http://p.pcxinfo.com/api/query/{}/{}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += str(key)
    _LOGGER.info('mishangpay_v4 sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("mishangpay_v4 sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'wxapp':
        return '2'
    elif service == 'cloud_flash':
        return '3'
    else:
        return '1'  # 支付宝


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_device_bundle(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('bundle') or ''


def _get_device_type(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_type') or 'android'


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('requestNo', str(pay.id)),
        ('transId', _get_pay_type(service)),
        ('merNo', app_id),
        ('goodsName', 'charge'),
        ('amount', str(int(pay_amount))),
        ('appUserId', str(pay.user_id)),
        ('notifyUrl', '{}/pay/api/{}/mishangpay_v4/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('passbackParams', 'charge'),
        ('signType', 'MD5'),
        ('timeStamp', local_now().strftime('%Y-%m-%d %H:%M:%S')),
    ))
    if service == 'wxapp':
        parameter_dict['ip'] = _get_device_ip(info)
        if _get_device_type(info) != 'android':
            parameter_dict['bundle'] = _get_device_bundle(info)
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    data = json.dumps(parameter_dict)
    url = _get_gateway(app_id)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    _LOGGER.info("mishangpay_v4 create: url: %s, %s", url, data)
    response = requests.post(url, data=data, headers=headers, timeout=5)
    _LOGGER.info("mishangpay_v4 create: response: %s", response.text)
    return {'charge_info': json.loads(response.text)['obj']['payInfo']}


# success
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("mishangpay_v4 notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['requestNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('mishangpay_v4 event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = 'success'
    trade_no = data['orderNo']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('mishangpay_v4 check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    url = _get_query_gateway(app_id).format(app_id, pay_id)
    _LOGGER.info(u'mishangpay_v4 query: %s', url)
    response = requests.get(url, verify=False)
    _LOGGER.info(u'mishangpay_v4 query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['obj']['status'])  # 0 订单未成功 1 订单成功
        total_fee = float(data['obj']['amount'])
        trade_no = data['obj']['orderNo']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('mishangpay_v4 query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('mishangpay_v4 data error, status_code: %s', response.status_code)
